import serial
import time
import signal
import sys

class RawSerialDumper:
    def __init__(self, port, baudrate=115200):
        self.ser = serial.Serial(
            port=port,
            baudrate=baudrate,
            timeout=0.1  # 非阻塞读取
        )
        # 根据SDK中的命令示例（可能需要调整）
        # self.command = bytes([0x01, 0x10, 0x01, 0x9A, 0x00, 0x01, 0x02, 0x00, 0x03, 0xEB, 0x6B])
        # self.command = bytes([0x01, 0x10, 0x01, 0x9A, 0x00, 0x01, 0x02, 0x00, 0x00, 0xAB, 0x6A])
        self.command = bytes([0x01, 0x04, 0x00, 0x00, 0x00, 0x0C, 0xF0, 0x0F])
        self.running = False

    def _dump_hex(self, data):
        """格式化输出十六进制数据"""
        return ' '.join(f'{b:02X}' for b in data)

    def start(self):
        try:
            if not self.ser.is_open:
                self.ser.open()
                print(f"已打开串口 {self.ser.name}，波特率 {self.ser.baudrate}")
            
            self.running = True
            self.ser.reset_input_buffer()
            
            # 发送初始化命令
            print(f"发送命令: {self._dump_hex(self.command)}")
            self.ser.write(self.command)
            
            # 主循环
            while self.running:
                # 读取数据
                data = self.ser.read_all()
                if data:
                    print(f"收到 {len(data)} 字节: {self._dump_hex(data)}")
                
                # 降低CPU占用
                time.sleep(0.1)
                
        except Exception as e:
            print(f"发生错误: {str(e)}")
        finally:
            self.stop()

    def stop(self):
        self.running = False
        if self.ser.is_open:
            self.ser.close()
            print("\n串口已关闭")

def signal_handler(sig, frame):
    print("\n检测到Ctrl+C，正在停止...")
    dumper.stop()
    sys.exit(0)

if __name__ == "__main__":
    # 配置参数（根据实际情况修改）
    PORT = "/dev/ttyUSB0"
    BAUD = 115200
    
    dumper = RawSerialDumper(PORT, BAUD)
    signal.signal(signal.SIGINT, signal_handler)
    
    print(f"启动原始数据监听（端口：{PORT}，按Ctrl+C退出）")
    dumper.start()